// presentation/viewmodel/DeviceDetailViewModel.kt
package com.hwpt.chesedemo.presentation.viewmodel

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hw.ble_lib.BleCallback
import com.hw.ble_lib.BleHelper
import com.hw.ble_lib.ChessMove
import com.hwpt.chesedemo.presentation.component.BtPreferences
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@HiltViewModel
class DeviceDetailViewModel @Inject constructor(
    @ApplicationContext private val context: Context,  // 添加 @ApplicationContext 注解
    private val btPreferences: BtPreferences,
    private val bleHelper: BleHelper
) : ViewModel() {

    private val _state = MutableStateFlow(DeviceDetailState())
    val state: StateFlow<DeviceDetailState> = _state

    private var currentDevice: BluetoothDevice? = null
    private var autoReconnect = true
    private val receivedDataBuilder = StringBuilder()
    private val timeFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())

    private val bleCallback = object : BleCallback {
        override fun onConnectionStateChanged(connected: Boolean) {
            viewModelScope.launch {
                _state.update {
                    it.copy(
                        isConnected = connected,
                        connectionStatus = if (connected) "连接状态：已连接" else "连接状态：已断开",
                        showDataSection = connected,
                        showMtuSection = connected
                    )
                }

                if (connected) {
                    currentDevice?.let { device ->
                        try {
                            btPreferences.saveDevice(device.address, device.name ?: "未知设备")
                        } catch (e: SecurityException) {
                            Log.e(TAG, "保存设备信息权限异常", e)
                        }
                    }
                } else if (autoReconnect) {
                    _state.update { it.copy(connectionStatus = "连接状态：重连中...") }
                    currentDevice?.address?.let { bleHelper.connect(it) }
                }
            }
        }

        override fun onDataReceived(data: ByteArray) {
            viewModelScope.launch {
                val timestamp = timeFormat.format(Date())
                val dataStr = if (_state.value.displayAsHex) bytesToHex(data) else String(data)

                receivedDataBuilder.append("[$timestamp]\n")
                receivedDataBuilder.append("原始: $dataStr\n\n")

                _state.update { it.copy(receivedData = receivedDataBuilder.toString()) }
            }
        }

        override fun onChessMoveReceived(chessMove: ChessMove?) {
            chessMove ?: return

            viewModelScope.launch {
                val timestamp = timeFormat.format(Date())
                receivedDataBuilder.append("━━━━━━━━━━━━━━━━\n")
                receivedDataBuilder.append("棋子移动\n")
                receivedDataBuilder.append(String.format("棋子: #%d\n", chessMove.pieceId))
                receivedDataBuilder.append(String.format("起点: (%d, %d)\n", chessMove.fromX, chessMove.fromY))
                receivedDataBuilder.append(String.format("终点: (%d, %d)\n", chessMove.toX, chessMove.toY))
                receivedDataBuilder.append("━━━━━━━━━━━━━━━━\n\n")

                _state.update { it.copy(receivedData = receivedDataBuilder.toString()) }
            }
        }

        override fun onDataSent(success: Boolean) {
            // 发送成功处理
        }

        override fun onError(error: String) {
            viewModelScope.launch {
                _state.update { it.copy(errorMessage = error) }
            }
        }
    }

    init {
        bleHelper.setCallback(bleCallback)
        val savedMtu = btPreferences.getSavedMtu()
        if (savedMtu > 0) {
            bleHelper.setMtu(savedMtu)
            _state.update { it.copy(currentMtu = savedMtu) }
        }
    }

    // 新增方法：从MAC地址初始化设备
    fun initializeFromAddress(deviceAddress: String, deviceName: String) {
        try {
            val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (bluetoothAdapter != null) {
                val device = bluetoothAdapter.getRemoteDevice(deviceAddress)
                setDevice(device, false)
            } else {
                _state.update {
                    it.copy(
                        deviceName = deviceName,
                        deviceAddress = "MAC: $deviceAddress",
                        errorMessage = "蓝牙适配器不可用"
                    )
                }
            }
        } catch (e: IllegalArgumentException) {
            _state.update {
                it.copy(
                    deviceName = deviceName,
                    deviceAddress = "MAC: $deviceAddress",
                    errorMessage = "无效的MAC地址: $deviceAddress"
                )
            }
        } catch (e: SecurityException) {
            _state.update {
                it.copy(
                    deviceName = deviceName,
                    deviceAddress = "MAC: $deviceAddress",
                    errorMessage = "缺少蓝牙权限"
                )
            }
        } catch (e: Exception) {
            _state.update {
                it.copy(
                    deviceName = deviceName,
                    deviceAddress = "MAC: $deviceAddress",
                    errorMessage = "初始化设备失败: ${e.message}"
                )
            }
        }
    }

    fun setDevice(device: BluetoothDevice, autoConnect: Boolean = false) {
        currentDevice = device
        val deviceName = try {
            device.name ?: "未知设备"
        } catch (e: SecurityException) {
            "未知设备"
        }

        _state.update {
            it.copy(
                deviceName = deviceName,
                deviceAddress = "MAC: ${device.address}",
                currentMtu = btPreferences.getSavedMtu(),
                errorMessage = null
            )
        }

        if (autoConnect) {
            connectDevice()
        }
    }

    fun connectDevice() {
        currentDevice?.let {
            _state.update { state ->
                state.copy(
                    connectionStatus = "连接状态：连接中...",
                    errorMessage = null
                )
            }
            bleHelper.connect(it.address)
        } ?: run {
            _state.update { state ->
                state.copy(
                    errorMessage = "设备信息未初始化"
                )
            }
        }
    }

    fun disconnectDevice() {
        autoReconnect = false
        _state.update {
            it.copy(
                autoReconnect = false,
                connectionStatus = "连接状态：断开中..."
            )
        }
        bleHelper.disconnect()
    }

    fun setAutoReconnect(enabled: Boolean) {
        autoReconnect = enabled
        _state.update { it.copy(autoReconnect = enabled) }
    }

    fun clearReceivedData() {
        receivedDataBuilder.clear()
        _state.update { it.copy(receivedData = "") }
    }

    fun setDisplayMode(hex: Boolean) {
        _state.update { it.copy(displayAsHex = hex) }
    }

    fun setSendMode(hex: Boolean) {
        _state.update { it.copy(sendAsHex = hex) }
    }

    fun setMtuInput(value: String) {
        _state.update { it.copy(mtuInput = value) }
    }

    fun setSendDataInput(value: String) {
        _state.update { it.copy(sendDataInput = value) }
    }

    fun saveMtu() {
        val mtuStr = _state.value.mtuInput.trim()
        if (mtuStr.isEmpty()) return

        try {
            val mtu = mtuStr.toInt()
            if (mtu in 23..517) {
                btPreferences.saveMtu(mtu)
                bleHelper.setMtu(mtu)
                _state.update { it.copy(currentMtu = mtu, mtuInput = "") }
            } else {
                _state.update { it.copy(errorMessage = "MTU值必须在23-517之间") }
            }
        } catch (e: NumberFormatException) {
            _state.update { it.copy(errorMessage = "请输入有效的数字") }
        }
    }

    fun sendData() {
        val input = _state.value.sendDataInput.trim()
        if (input.isEmpty()) return

        if (_state.value.sendAsHex) {
            bleHelper.sendHexString(input)
        } else {
            bleHelper.sendData(input.toByteArray())
        }
    }

    private fun bytesToHex(bytes: ByteArray): String {
        return bytes.joinToString("") { "%02X ".format(it) }.trim()
    }

    override fun onCleared() {
        super.onCleared()
        autoReconnect = false
        bleHelper.release()
    }

    companion object {
        private const val TAG = "DeviceDetailViewModel"
    }
}

data class DeviceDetailState(
    val deviceName: String = "",
    val deviceAddress: String = "",
    val connectionStatus: String = "连接状态：未连接",
    val isConnected: Boolean = false,
    val autoReconnect: Boolean = true,
    val displayAsHex: Boolean = true,
    val sendAsHex: Boolean = true,
    val receivedData: String = "",
    val currentMtu: Int = 27,
    val mtuInput: String = "",
    val sendDataInput: String = "",
    val showDataSection: Boolean = false,
    val showMtuSection: Boolean = false,
    val errorMessage: String? = null
)